package com.day16;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 创建线程的方式四:使用线程池
 */


class NumberDemo implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}

class NumberDemo1 implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 != 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}


public class ThreadPool {

    public static void main(String[] args) {


        //1.提供指定线程数量的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executorService;

        //设置线程池的属性,getClass获取对象是哪个类创建的
        System.out.println(executorService.getClass());

        //设置核心池的大小
        threadPoolExecutor.setCorePoolSize(15);

        //设置线程没有任务时最多保持多长时间
//        threadPoolExecutor.setKeepAliveTime();

        //设置maximumPoolSize:最大线程数
//        threadPoolExecutor.setMaximumPoolSize();

        //2.执行指定的线程的操作，需要提供实现Runnable接口或Callable接口实现类的对象
        executorService.execute(new NumberDemo()); //适合使用于Runnable
        executorService.execute(new NumberDemo1()); //适合使用于Runnable
        executorService.submit(new NumberThread());//适合使用于Callable

        //线程池不用了，可以做关闭
        executorService.shutdown();

    }

}
